/**
 * 
 */
package lv.pig.base.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lv.pig.base.constants.BasePageConstants;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * 登录,退出,验证码等
 * 
 * @author chenbo
 *
 */
@Controller
public class SystemController
{
    
    @Autowired(required = false)
    Producer captchaProducer;
    
    @Autowired
    HttpSession session;
    
    private transient static final Logger logger = LoggerFactory.getLogger(SystemController.class);
    
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login()
    {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated())
        {
            return "redirect:/home";
        }
        return BasePageConstants.login;
    }
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model, HttpServletRequest request)
    {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() || subject.isRemembered())
        {
            return "redirect:/home";
        }
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String loginKaptchaCode = request.getParameter("verifyCode");
        
        Session shiroSession = subject.getSession();
        Object kaptchaCode = shiroSession.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        
        if (kaptchaCode != null && !StringUtils.equalsIgnoreCase(loginKaptchaCode, kaptchaCode.toString()))
        {
            model.addAttribute("message", "验证码错误!");
            return BasePageConstants.login;
        }
        
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false, request.getRemoteHost());
        try
        {
            subject.login(token);
            
            return "redirect:/home";
        }
        catch (UnknownAccountException uae)
        {
            model.addAttribute("message", "用户名不存在!");
            logger.info("Unknown User!");
        }
        catch (IncorrectCredentialsException ice)
        {
            model.addAttribute("message", "密码不正确!");
            logger.info("Incorrect Password!");
        }
        catch (LockedAccountException lae)
        {
            model.addAttribute("message", "用户被锁!");
            logger.info("User Locked!");
        }
        catch (AuthenticationException ae)
        {
            model.addAttribute("message", "验证失败!");
            logger.info("Authentication Failed!");
        }
        return BasePageConstants.login;
    }
    
    @RequestMapping("api/verifycode")
    public String verifycode(HttpServletResponse response)
        throws Exception
    {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try
        {
            out.flush();
        }
        finally
        {
            out.close();
        }
        return null;
    }
}
